package com.nipun.graph.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import org.apache.xerces.parsers.DOMParser;
import org.apache.xml.serialize.DOMSerializer;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.jaxen.JaxenException;
import org.jaxen.SimpleNamespaceContext;
import org.jaxen.SimpleVariableContext;
import org.jaxen.dom.DOMXPath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLUtils {
	
	public static Document getDOM(File file){
		Document doc = getDOMDocument(new InputSource(file.getAbsolutePath()));
		
		return doc;
	}
	
	public static Document getDOMDocument(InputSource is){
		Document document = null;
		DOMParser parser = new DOMParser();
		try {
			parser.parse(is);
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		document = parser.getDocument();
		return document;
	}
	
	public static void printDocument(Document document){
		DOMSerializer ser = new XMLSerializer(new OutputStreamWriter(System.out), new OutputFormat());
		try {
			ser.serialize(document);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Object[] evalXPath(Element el, String xPathExpr, Element ctx){
		Object[] nodes = null;
		try {
			DOMXPath xpath = new DOMXPath(xPathExpr);
			xpath.setVariableContext(new SimpleVariableContext());
			if(ctx==null){
				xpath.setNamespaceContext(new SimpleNamespaceContext(new HashMap(
						11, 1.0f)));
			}else{
				xpath.setNamespaceContext(new DerivedNameSpaceContext(ctx,new Hashtable(
						11, 1.0f)));
			}
			Object result = xpath.evaluate(el);
			if (List.class.isAssignableFrom(result.getClass())) {
				List nodeList = (List) result;
				Object[] nodeArray = new Object[nodeList.size()];
				nodes = nodeList.toArray(nodeArray);
			} else {
				nodes = new Object[1];
				nodes[0] = result;
			}
		} catch (JaxenException e) {
			e.printStackTrace();
		}
		return nodes;
	}
	
	public static void writeDocumentToDisk(String filePath, Document document){
		try {
			FileWriter fw = new FileWriter(new File(filePath));
			DOMSerializer ser = new XMLSerializer(fw, new OutputFormat());
			ser.serialize(document);
//			String buffer = sw.toString();
//			System.out.println(buffer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
